<template>
    <el-card shadow="hover">
<!--      条件查询-->
      <el-form :inline="true" :model="studentSearch" class="demo-form-inline" size="medium">
        <el-form-item >
          <el-input v-model="studentSearch.sname" placeholder="学生姓名" />
        </el-form-item>
        <el-form-item >
          <el-input v-model="studentSearch.addr" placeholder="学生住址" />
        </el-form-item>
        <el-form-item label="学生班级">
          <el-select v-model="studentSearch.cid" placeholder="选择班级">
            <el-option label="所有班级" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classes"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" icon="el-icon-search" plain>查询</el-button>
        </el-form-item>
<!--        添加-->
        <el-form-item>
          <el-button type="success" @click="add" icon="el-icon-plus" plain>添加</el-button>
        </el-form-item>
      </el-form>
    <el-table
     :data="students"
    style="width: 100%">
    <el-table-column
      label="学号"
      prop="sid"
      align="center"
      width="180" />
    <el-table-column
      label="姓名"
      prop="sname"
      align="center" />
      <el-table-column
          label="性别"
          prop="sex"
          align="center" />
      <el-table-column
          label="年龄"
          prop="age"
          align="center" />
      <el-table-column
          label="班级"
          prop="cname"
          align="center" />
      <el-table-column
          label="住址"
          prop="addr"
          align="center" />
    <el-table-column label="操作" align="center" >

      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
<!--      分页导航-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
<!--      编辑学生对话框-->
      <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
        {{student}}
        <el-form :model="student" :rules="rules" ref="ruleForm">
          <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
            <el-input v-model="student.sname" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="学生性别" :label-width="formLabelWidth" prop="sex">
            <el-radio v-model="student.sex" label="男">男</el-radio>
            <el-radio v-model="student.sex" label="女">女</el-radio>
          </el-form-item>
          <el-form-item label="学生年龄" :label-width="formLabelWidth" prop="age">
            <el-input v-model.number="student.age" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="学生地址" :label-width="formLabelWidth" prop="addr">
            <el-input v-model="student.addr" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="所在班级" :label-width="formLabelWidth" prop="cid">
            <el-select v-model="student.cid" placeholder="请选择所在班级">
              <el-option :label="c.cname" :value="c.cid" v-for="c in classes"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </el-dialog>
   </el-card>
</template>

<script>
  export default {
    data() {
      var checkAge = (rule, value, callback) => {
        if (value.length<=0) {
          return callback(new Error('年龄不能为空'));
        } else if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else if (value < 1 || value > 150) {
          callback(new Error('年龄必须1~150之间'));
        } else {
          callback();
        }
      }
      return {

        students: [],
        page:1,//当前页
        pageSize:5,//每页大小
        total:100,//总记录数
        title:'添加学生',//对话框标题
        studentSearch:{},//查询条件
        classes:[],   //所有班级列表
        dialogFormVisible:false,//对话框是否可见
        student: {}, //添加或修改的学生对象
        formLabelWidth: '100px',//表单项的标签宽度
        // 定义验证规则
        rules: {
          sname: [
            { required: true, message: '请输入学生姓名', trigger: 'blur' },
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          age: [
              // { required: true, message: '请输入年龄', trigger: 'blur' },
            {validator: checkAge, trigger: 'blur'}

          ],
          addr: [
            { required: true, message: '请输入地址', trigger: 'blur' }
          ],
          cid: [
            { required: true, message: '请选择班级', trigger: 'change' }
          ]
        }
      }
    },
    created() {
      //查询所有学生列表
      // this.getStudents()
      // 2.分页查询学生
      // this.findByPage()
      this.search()
      // 查询所有班级列表
      this.findClasses()

    },
    methods: {

      //保存函数
      save(){
        //第一步进行表单检验
        this.$refs['ruleForm'].validate(valid => {//valid为true表示表单验证成功,有一个不通过就是false
          if(valid){
            //不管添加还是修改提交都是student对象，只不过是地址不一样
            let url = '/student?cmd=add'
            //如何区分添加和修改 是否有sid
            if(this.student.sid){//修改
              url = '/student?cmd=update'
            }
            //最后提交到后台
            this.$axios.post(url,this.student).then(resp => {
              if(resp.data.code == '200'){//成功了
                //提示信息
                //关闭对话框
                this.dialogFormVisible = false
                //刷新列表
                this.search()
                //提示信息
                this.$message({
                  type: 'success',
                  message: resp.data.message
                })
              }else {
               //添加失败
                this.$message.error(resp.data.message)
              }
            })
          }else {
            console.log("表单验证失败")
            return false;
          }
        })
      },
      //条件查询
      search(){
        this.$axios.post(`/student?cmd=search&page=${this.page}&pageSize=${this.pageSize}`,
            this.studentSearch).then(res => {
          this.students = res.data.rows
          this.total = res.data.total
          console.log(res)
        })
      },
      //定义普通方法
      getStudents() {
        this.$axios.get('/student?cmd=list').then(res => {
          //请求成功
          this.students = res.data
        })
      },
      // 分页查询
      findByPage(){
        this.$axios.get(`/student?cmd=findByPage&page=${this.page}&pageSize=${this.pageSize}`).then(res => {
          console.log(res)
          this.students = res.data.rows
          this.total = res.data.total
        })
      },
      //查询所有的班级
      findClasses(){
        this.$axios.get('/classes').then(res => {
          this.classes = res.data
        })
      },
      // 添加学生
      add(){
        // 设置标题
        this.title = "添加学生"
        //重置数据
        this.student = {}
        //显示对话框

        this.dialogFormVisible = true
      },
      // 每页大小改变触法
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val
        //this.findByPage()
        this.search()
      },
      //当前页改变
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.page = val
        //this.findByPage()
        this.search()
      },
      // 编辑学生
      handleEdit(index, row) {
        console.log(index, row);
        //为student对象赋值
        this.student = row
        //为标题赋值
        this.title = "修改学生"
        //显示对话框
        this.dialogFormVisible = true
      },
      handleDelete(index, row) {
        console.log(index, row);
      }
    }
  }
</script>

<style>
.el-card{
  width: 90%;
  margin: 20px auto;
}
.el-pagination {
  text-align: right;
  margin-top: 20px;
}
</style>
